package com.bigger.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bigger.constant.ErrorConstant;
import com.bigger.constant.MqConstant;
import com.bigger.context.BaseContext;
import com.bigger.dto.BusinessPageDTO;
import com.bigger.dto.UpdateBusinessDTO;
import com.bigger.entity.Business;
import com.bigger.exception.BaseException;
import com.bigger.exception.DeleteException;
import com.bigger.mapper.BusinessMapper;
import com.bigger.result.PageResult;
import com.bigger.service.BusinessService;
import com.bigger.utils.MinIOUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Objects;
import java.util.UUID;

@Service
public class BusinessServiceImpl implements BusinessService {
    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private MinIOUtil minIOUtil;

    @Override
    public PageResult<Business> page(BusinessPageDTO businessPageDTO) {
        Page<Business> page = new Page<>(businessPageDTO.getPage(), businessPageDTO.getPageSize());
        QueryWrapper<Business> wrapper = new QueryWrapper<Business>()
                .like(businessPageDTO.getName() != null && !businessPageDTO.getName().isEmpty(),
                        "name", businessPageDTO.getName()
                )
                .eq(businessPageDTO.getStatus() != null, "status", businessPageDTO.getStatus());
        Page<Business> businessPage = businessMapper.selectPage(page, wrapper);
        if (businessPage.getRecords().isEmpty()) {
            page = new Page<>(1, businessPageDTO.getPageSize());
            businessPage = businessMapper.selectPage(page, wrapper);
        }
        PageResult<Business> pageResult = new PageResult<>(businessPage.getTotal(), businessPage.getRecords());
        return pageResult;
    }

    @Override
    public void addBusiness(UpdateBusinessDTO updateBusinessDTO) {
        Business business = new Business();
        LocalDateTime now = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
        business.setName(updateBusinessDTO.getName());
        business.setImage(updateBusinessDTO.getImage());
        business.setPrice(updateBusinessDTO.getPrice());
        business.setStatus(Business.UP_BUSINESS);//默认新添加的商品为上架模式
        business.setInfo(updateBusinessDTO.getInfo());
        business.setCreateTime(now);
        business.setUpdateTime(now);
        business.setCreateUser(BaseContext.getCurrentId());
        business.setUpdateUser(BaseContext.getCurrentId());
        businessMapper.insert(business);
        rabbitTemplate.convertAndSend(MqConstant.XHDN_EXCHANGE, MqConstant.XHDN_INSERT_KEY, business.getId());
    }

    @Override
    public void update(UpdateBusinessDTO updateBusinessDTO) {
        Business updateBusiness = new Business();
        Business business = businessMapper.selectById(updateBusinessDTO.getId());
        String image = business.getImage();
        if (
                !StringUtils.isBlank(updateBusinessDTO.getImage())
                        &&
                !updateBusinessDTO.getImage().equals(image)
        ) {
            updateBusiness.setImage(updateBusinessDTO.getImage());
            minIOUtil.deleteFile(getImageName(image)); //删除原图片
        }
        updateBusiness.setId(updateBusinessDTO.getId());
        updateBusiness.setName(updateBusinessDTO.getName());
        updateBusiness.setStatus(updateBusinessDTO.getStatus());
        updateBusiness.setPrice(updateBusinessDTO.getPrice());
        updateBusiness.setInfo(updateBusinessDTO.getInfo());
        updateBusiness.setUpdateTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
        updateBusiness.setUpdateUser(BaseContext.getCurrentId());
        businessMapper.updateById(updateBusiness);
        rabbitTemplate.convertAndSend(MqConstant.XHDN_EXCHANGE, MqConstant.XHDN_INSERT_KEY, updateBusiness.getId());
    }

    @Override
    public void delete(Long id) {
        Business business = businessMapper.selectById(id);
        if (business == null) {
            throw new DeleteException(ErrorConstant.ID_NOT_EXIT);
        }
        minIOUtil.deleteFile(getImageName(business.getImage()));
        businessMapper.deleteById(id);
        rabbitTemplate.convertAndSend(MqConstant.XHDN_EXCHANGE, MqConstant.XHDN_DELETE_KEY, id);
    }

    @Override
    public Business getById(Long id) {
        Business business = businessMapper.selectById(id);
        return business;
    }

    /**
     * 获取到对应的图片名称
     * 好对其进行删除
     * @param image
     * @return
     */
    private String getImageName(String image) {
        int i = image.lastIndexOf("/");
        String imageName = image.substring(i + 1);
        return imageName;
    }
}
